<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >裁判员</el-breadcrumb-item
          >
          <el-breadcrumb-item :to="{ name: 'RefereeExamList' }"
            >认证答题管理</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="exam_from_content">
        <!-- 表单 -->
        <el-row>
          <el-col :span="22">
            <el-form
              ref="submitFrom"
              :model="submitData"
              label-width="140px"
              :rules="rules"
              :disabled="editKey == 3"
            >
              <el-form-item label="标题:" size="small" prop="title" required>
                <el-col :span="8">
                  <el-input
                    v-model="submitData.title"
                    maxlength="20"
                    placeholder="请输入标题"
                  ></el-input>
                </el-col>
              </el-form-item>

              <el-form-item
                label="视频链接:"
                size="small"
                prop="video_url"
                required
              >
                <el-col :span="8">
                  <el-input
                    v-model="submitData.video_url"
                    placeholder="请输入视频链接"
                  ></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="类型:" size="small" prop="type" required>
                <el-col :span="8">
                  <el-select
                    style="width: 100%"
                    v-model="submitData.type"
                    placeholder="请选择类型"
                  >
                    <el-option
                      v-for="(item, index) in typeList"
                      :key="index"
                      :label="item.value"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-form-item>
              <el-form-item label="答案解析:" size="small" prop="analysis">
                <el-col :span="8">
                  <el-input
                    type="textarea"
                    v-model="submitData.analysis"
                    resize="none"
                    :rows="5"
                  ></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="选项:" size="small" prop="options" required>
                <el-col :span="16">
                  <el-row
                    v-for="(item, index) in submitData.options"
                    :key="index"
                    style="margin-bottom: 10px"
                  >
                    <el-col :span="10">
                      <el-input
                        v-model="item.content"
                        placeholder="请输入选项内容"
                      ></el-input>
                    </el-col>
                    <el-col :span="10" style="margin-left: 20px">
                      <el-radio-group v-model="item.is_correct">
                        <el-radio label="1">正确</el-radio>
                        <el-radio label="2">错误</el-radio>
                      </el-radio-group>
                      <el-button
                        style="margin-left: 20px"
                        type="danger"
                        size="mini"
                        @click="deleteOptionFn(item, index)"
                        >删除</el-button
                      >
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-button type="primary" size="mini" @click="addOptionFn()"
                      >新增</el-button
                    >
                  </el-row>
                </el-col>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-row>
    <div class="exam_from_btn_box" v-if="editKey != 3">
      <el-button type="danger" size="mini" @click="saveBtn()">保存</el-button>
      <el-button type="info" size="mini" @click="backBtn()"
        >返回上一页</el-button
      >
    </div>
    <div class="exam_from_btn_box" v-else>
      <el-button type="danger" size="mini" @click="backBtn()">返回</el-button>
    </div>
  </div>
</template>
<style src="../../assets/css/referee/examForm.css" scoped></style>

<script>
export default {
  name: "RefereeExamForm",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl, //默认路径
      actionUrl: this.$store.state.baseAPIUrl + "/upload/uploadFile", // 上传路径
      // actionUrl: "/upload/uploadImage", // 上传路径
      imageShowUrl: "", // 预览路径
      uploadData: {
        source: 5,
      }, // 上传额外参数
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      examId: "", // 培训科目id
      pageTitle: "", // 页面名称
      editKey: 1, // 是否编辑
      submitData: {
        title: "",
        video_url: "",
        type: "",
        analysis: "",
        options: [],
      }, // 培训数据
      rules: {
        title: [{ required: true, message: "请输入培训名称", trigger: "blur" }],
        video_url: [
          { required: true, message: "请输入视频链接", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择报类型", trigger: "change" }],
        options: [{ validator: this.validateOptions }],
      }, // 校验规则
      format: "yyyy 年 MM 月 dd 日",
      valueFormat: "yyyy-MM-dd",
      formatTime: "HH:mm",
      valueFormatTime: "HH:mm",
      loadingKey: false,
      loadingText: "",
      typeList: [
        {
          key: 1,
          value: "单选",
        },
        // {
        //   key: 2,
        //   value: "单选",
        // },
        {
          key: 3,
          value: "多选",
        },
        // {
        //   key: 4,
        //   value: "问答",
        // },
      ], // 答题类型
    };
  },
  created: function () {
    let query = this.$route.query;
    if (query.id != undefined && query.id != "") {
      this.examId = query.id;
    }

    if (query.key != undefined && query.key != "") {
      this.editKey = query.key;
    }

    if (this.editKey == 2) {
      this.pageTitle = "编辑答题";
    } else if (this.editKey == 1) {
      this.pageTitle = "新增答题";
      this.examId = "";
    } else {
      this.pageTitle = "查看答题";
    }
    if (this.editKey != 1 && this.examId != false) {
      this.getDataFn();
    }
  },
  mounted: function () {},
  methods: {
    // 查询答题详情
    getDataFn: function () {
      let that = this;
      let url = "/admin/question/show";
      let data = {
        id: this.examId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            console.log(response);
            that.submitData.title = response.question.title;
            that.submitData.video_url = response.question.video_url;
            that.submitData.type = response.question.type;
            that.submitData.analysis = response.question.analysis;
            let optionsList = [];
            response.question.option.forEach((i) => {
              let obj = {
                id: i.id,
                content: i.content,
                is_correct: i.is_correct + "",
              };
              optionsList.push(obj);
            });

            that.submitData.options = optionsList;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 提交保存
    saveBtn: function () {
      let that = this;
      let url = "";
      let data = {
        title: this.submitData.title,
        video_url: this.submitData.video_url,
        type: this.submitData.type,
        analysis: this.submitData.analysis,
      };
      let optionsList = [];
      if (this.editKey == 1) {
        url = "/admin/question/store";
        this.submitData.options.forEach((item) => {
          let obj = {
            content: item.content,
            is_correct: item.is_correct,
          };
          optionsList.push(obj);
        });
        data.options = optionsList;
      } else {
        url = "/admin/question/update";
        this.submitData.options.forEach((item) => {
          let obj = {
            id: item.id,
            content: item.content,
            is_correct: item.is_correct,
          };
          optionsList.push(obj);
        });
        data.options = optionsList;
        data.id = this.examId;
      }
      this.$refs.submitFrom.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("保存成功");
                that.backBtn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 添加选项
    addOptionFn: function () {
      let obj = {
        id: 0,
        content: "",
        is_correct: "",
      };
      this.submitData.options.push(obj);
    },
    // 删除选项
    deleteOptionFn: function (item, index) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        if (item.id != 0) {
          let url = "/admin/question/deleteOption";
          let data = {
            opt_id: item.id,
          };
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.submitData.options.splice(index, 1);
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        } else {
          this.submitData.options.splice(index, 1);
        }
      });
    },
    // 验证选项
    validateOptions: function (rule, value, callback) {
      let that = this;
      if (value.length < 2) {
        callback(new Error("请添加至少2个选项"));
      } else {
        console.log(value);
        let type = that.submitData.type;
        let i = 0;
        value.forEach((item) => {
          if (item.is_correct == 1) {
            i++;
          }
        });
        if (type == 1 && i > 1) {
          callback(new Error("正确选项不能多于1个"));
        } else if (i == 0) {
          callback(new Error("正确选项不能少于1个"));
        } else {
          callback();
        }
      }
    },
    // 返回上一页
    backBtn: function () {
      this.$router.replace({
        name: "RefereeExamList",
      });
    },
  },
};
</script>
